package wnhz.com.business.shareshop.activity.home;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.netcallback.DialogCallback;
import wnhz.com.business.rebateshop.activity.home.ShareFriandActivity;
import wnhz.com.business.shareshop.activity.classify.ClassifGoodsActivity;
import wnhz.com.business.shareshop.activity.classify.fragment.ClassifGoodsFragment;
import wnhz.com.business.shareshop.bean.F2TypeGoodsListBean;
import wnhz.com.business.shareshop.bean.SearchResultBean;
import wnhz.com.business.shareshop.bean.ShareHomDataBean;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.view.TranslucentActionBar;

import static wnhz.com.business.R.id.actionbar;

/**
 * Created by Administrator on 2017-12-15 0015.
 * 商品种类从首页跳转过来
 */

public class ClassFromHomeActivity extends BaseActivity implements ActionBarClickListener, OnRefreshLoadmoreListener {
    @BindView(R.id.recycler_View)
    RecyclerView recyclerView;
    @BindView(R.id.empty_layout)
    LinearLayout empty_layout;
    @BindView(R.id.tv_msg)
    TextView tv_msg;
    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private List<F2TypeGoodsListBean.InfoBean> itemdata = new ArrayList<>();
    private String cate_id,title;
    private BaseRVAdapter mBaseAdapter;


    public static ClassifGoodsFragment getInstance() {
        ClassifGoodsFragment cf = new ClassifGoodsFragment();
        return cf;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify_goods_home);
        ButterKnife.bind(this);
        if(null!=getIntent()){
            title =getIntent().getStringExtra("title");
            cate_id =getIntent().getStringExtra("cate_id");
        }
        actionbar.setData(title, R.drawable.ic_lefft_white, null, 0, "", 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }
        initTestGallylist();
    }

    private int page = 0;

    private void loadData() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        map.put("cateId", cate_id);
        map.put("goods_type", "4");
        map.put("page", page+"");
        /**
         根据指定商品分类查询商品数据
         @param   Str     token
         @param   Int     cateId      (一级分类id或二级分类id)  首次请求用一级分类ID，之后使用二级分类ID
         @param   Int     goods_type  1.拼团  2.返利  3.免费
         @param   Int     page        页码
         */
        XUtil.Post(Url.GOODS_GETCATEGOODS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LogUtils.e("----------------", "---------------" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("re");
                    if (re.equals("1")) {
                        Gson gson = new Gson();
                        F2TypeGoodsListBean f2TypeGoodsListBean = gson.fromJson(result, F2TypeGoodsListBean.class);

                        if (page == 0){
                            if (null != itemdata){
                                itemdata.clear();
                            }
                            itemdata = f2TypeGoodsListBean.getInfo();
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                        }else {
                            mRefreshLayout.finishLoadmore();
                            mBaseAdapter.notifyDataSetChanged();

                        }
                        initList();
                    }else if ("-1".equals(jsonObject.optString("re"))){
                       MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        if (page == 0){
                            mRefreshLayout.setVisibility(View.GONE);
                            empty_layout.setVisibility(View.VISIBLE);
                            MyToast(jsonObject.optString("info"));
                            tv_msg.setText("暂无商品");
                        }else {
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();//将不会再次触发加载更多事件
                            empty_layout.setVisibility(View.GONE);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                if (itemdata != null && itemdata.size() > 0) {
                    empty_layout.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.VISIBLE);
                    initList();
                } else {
                    empty_layout.setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.GONE);
                    tv_msg.setText("暂无商品");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    private void initTestGallylist() {
        recyclerView.setLayoutManager(new GridLayoutManager(ClassFromHomeActivity.this, 2, GridLayoutManager.VERTICAL, false));
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        loadData();
    }

    private void initList() {

        // holder.setTextView(R.id.item_tv_rebatehome_info,itemdata.get(position).get());
         //跳转分享页面  (页面标题: 分享商品给好友)
        mBaseAdapter = new BaseRVAdapter(ClassFromHomeActivity.this, itemdata) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_classify_phone;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                Glide.with(ClassFromHomeActivity.this).load(itemdata.get(position).getLogo_pic()).into(holder.getImageView(R.id.item_img_rebatehome));
                holder.setTextView(R.id.item_tv_rebatehome_name, itemdata.get(position).getGoods_name());
                holder.setTextView(R.id.item_tv_rebatehome_info,itemdata.get(position).getGoods_title() + " " + itemdata.get(position)
                        .getGoods_des());
                holder.setTextView(R.id.item_tv_rebatehome_price, "押金" + itemdata.get(position).getPrice() + "元");
                holder.getView(R.id.item_tv_rebatehome_share).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //跳转分享页面  (页面标题: 分享商品给好友)
                        startActivity(ShareFriandActivity.createIntent(ClassFromHomeActivity.this, itemdata.get(position).getLogo_pic(), "", itemdata.get(position).getGoods_name(), itemdata.get(position).getGroup_price()));
                    }
                });
                holder.getView(R.id.item_rl_rebatehome).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(RebateGoodsDetailsActivityS.createIntent(ClassFromHomeActivity.this, itemdata.get(position).getGoods_id(), itemdata.get(position).getLogo_pic(), "4"));
                    }
                });
            }

        };
        recyclerView.setAdapter(mBaseAdapter);
    }


    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onEditTextClick() {

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = page + 1;
                loadData();
            }
        },2000);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 0;
                loadData();
            }
        },2000);
    }
}